<?php
namespace common\behaviors;

use Yii;
use yii\base\Event;
use yii\db\BaseActiveRecord;
use yii\behaviors\AttributeBehavior;

/**
 * Class UserIpBehavior
 * @author Xuegui Yuan <yuanxuegui@163.com>
 */
class UserIpBehavior extends AttributeBehavior
{
    /**
     * @var string
     */
    public $userIpAttribute = 'user_ip';

    /**
     * @var callable the value that will be assigned to the attributes. This should be a valid
     * PHP callable whose return value will be assigned to the current attribute(s).
     * The signature of the callable should be:
     *
     * ```php
     * function ($event) {
     *     // return value will be assigned to the attribute(s)
     * }
     * ```
     *
     * If this property is not set, the value of `Yii::$app->request->userIP` will be assigned to the attribute(s).
     */
    public $value;


    /**
     * @inheritdoc
     */
    public function init()
    {
        parent::init();

        if (empty($this->attributes)) {
            $this->attributes = [
                BaseActiveRecord::EVENT_BEFORE_INSERT => [$this->userIpAttribute],
                BaseActiveRecord::EVENT_BEFORE_UPDATE => false,
            ];
        }
    }

    /**
     * Evaluates the value of the user.
     * The return result of this method will be assigned to the current attribute(s).
     * @param Event $event
     * @return mixed the value of the user.
     */
    protected function getValue($event)
    {
        if ($this->value === null) {
            return Yii::$app->request->userIP;
        } else {
            return call_user_func($this->value, $event);
        }
    }
}
